import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetSeed {
    public static void main(String[] args) throws IOException, InterruptedException {
        while(true){
            downloadNet();
            Thread.sleep(60000 );
       }
    }
    private static HttpURLConnection con;
    private static int state = -1;
    public static void downloadNet() throws IOException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        Date now = new Date();
        SimpleDateFormat dateFormatHour= new SimpleDateFormat("yyyy-MM-dd-HH");
        String  hour = dateFormatHour.format( now );
        SimpleDateFormat dateFormatMinute= new SimpleDateFormat("yyyy-MM-dd-HH-mm");
        String  minute = dateFormatMinute.format( now );

        String filePath = System.getProperty("java.class.path");
        String pathSplit = System.getProperty("path.separator");//得到当前操作系统的分隔符，windows下是";",linux下是":"

        if(filePath.contains(pathSplit)){
            filePath = filePath.substring(0,filePath.indexOf(pathSplit));
        }else if (filePath.endsWith(".jar")) {//截取路径中的jar包名,可执行jar包运行的结果里包含".jar"
            filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);
        }
        File dir = new File(filePath+hour+"\\");
        File file = new File(filePath+hour+"\\"+minute);
        //判断日期文件夹是否存在，不存在的话创建
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        //判断文件是否存在，不存在的话创建
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //URL url = new URL("http://knowledge0603.fun/bt/P001001.torrent");
        URL url = new URL("http://knowledge0603.fun/bt/"+minute+".torrent");

        con = (HttpURLConnection) url.openConnection();
        state = con.getResponseCode();
        if (state == 200) {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(filePath+hour+"\\"+minute);

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            fs.close();
        }
    }
}
